﻿public class Solution {
    public int[] TopKFrequent(int[] nums, int k)
    {
        int[] res = new int[k];
        Dictionary<int, int> dic = new Dictionary<int, int>();
        PriorityQueue<int, int> priQueue = new PriorityQueue<int, int>();

        foreach (int n in nums)
        {
            dic[n] = dic.GetValueOrDefault(n, 0) + 1;
        }

        foreach (int key in dic.Keys)
        {
            priQueue.Enqueue(key, dic[key]);
            if (priQueue.Count > k)
            {
                priQueue.Dequeue();
            }
        }

        for (int i = res.Length - 1; i >= 0; i--)
        {
            res[i] = priQueue.Dequeue();
        }
        return res;
    }

    public static void Main(string[] args)
    {
        int[] nums = [1, 1, 1, 2, 2, 3];
        int k = 2;

        Solution solution = new Solution();
        int[] res = solution.TopKFrequent(nums, k);

        foreach (int r in res)
        {
            Console.Write($"{r} ");
        }
    }
}